<?php

class messageHelper extends helperBase {

	protected $messages = array();

	function toArray($object) {
		if(is_object($object)) {
			$array = (array) $object;
			foreach($array as $key => $element) {
				$array[$key] = $this->toArray($element);
			}
			return $array;
		} else {
			return $object;
		}
	}

	function init() {
		if(isset($_COOKIE['aetherMessage'])) {
			$change = false;
			$this->messages = json_decode($_COOKIE['aetherMessage']);
			$this->messages = $this->toArray($this->messages);
			foreach($this->messages as $key => $message) {
				if($message['expires']!=0 && $message['expires']<time()) {
					$this->messages[$key]['closed'] = true;
					$change = true;
				}
			}
			if($change) {
				$this->applyChanges();
			}
		}
		require('app/config/globalMessages.php');
	}

	function add($message, $expires = 10, $attr = array(), $key = false) {
		if($expires) {
			$expires += time();
		}
		if(isset($this->messages[$key])) {
			return;
		}
		if($key===false) {
			$key = generateKey(16);
		}
		$this->messages = arrayAppend($this->messages, array(
			$key => array(
				'message' => $message,
				'expires' => $expires,
				'attr' => $attr,
				'closed' => false
			)
		));
		$this->applyChanges();
	}

	function listMessages($url) {
		reset($this->messages);
		$return = '';
		if($this->hasMessages()) {
			$return .= '<div class="flash">';
			foreach($this->messages as $key => $message) {
				if(!$message['closed']) {
					$message['attr'] = arrayExtend($message['attr'], array(
						'id' => 'aether-message-'.$key
					));
					$return .= $this->h->html->open('p', $message['attr']);
					$message['message'] = str_replace('[pageUrl]', $this->h->core->getUrl(), $message['message']);	
					$return .= $message['message'];
					if($message['expires']!=0) {
						$return .= '<script type="text/javascript"><!-- setTimeout("alert(\'Awesome\'); aether.closeMessage(\''.$key.'\', false);", '.(($message['expires'] - time())).'); alert("Frickin sweet!"); --></script>';
					}
					$return .= $this->h->html->open('a', array(
						'href' => 'aether/closeMessage/'.$key.'/?urlToPhp=0&redirect='.urlencode($url),
						'class' => 'closer',
						'onclick' => 'aether.closeMessage(\''.$key.'\', true); return false;'
					), array('content' => 'Close')); 
					$return .= $this->h->html->close();
				}
			}
			$return .= '</div>';
		}
		return $return;
	}

	function hasMessages() {
		foreach($this->messages as $message) {
			if(!$message['closed']) {
				return true;
			}
		}
		return false;
	}

	function closeMessage($key) {
		$this->messages[$key]['closed'] = true;
		$this->applyChanges();
	}

	function applyChanges() {
		setcookie('aetherMessage', json_encode($this->messages), time() +60*60*24*365, $this->aether->config->get('general', 'webRoot'));
	}

}

?>
